

import React, { Component } from "react";
import { FlatList, RefreshControl, SafeAreaView, ActivityIndicator, StyleSheet, Text, Alert, TouchableOpacity, View , Platform} from 'react-native';
import AppListItem from "../components/AppListItem/AppListItem";
import UserManager from "../common/UserManager";
import {getAppCategorysApi, getAppsByCategorysIdApi} from '../api/AppApi'
import { AppInfo,queryAppList, insertAppInfos } from "../database/AppInfo";
import FileUtil from "../utils/FileUtils";
import Constants from "../common/Constants";
import RNFS from 'react-native-fs';
import ToastUtils from "../components/ToastUtils";
import ProgressHub from "../components/ProgressHub/ProgressHub"

export default class AppListPage extends Component{

    constructor(props) {
        super(props);
        this.state = {
          appList: [],
          userInfo: {},
          ticket: '',
          refreshing: false,
          installedList:[],
          progress: 0,
          isShowProgress: false
        };

       this.getDefaultValue()
       
      }


    async getDefaultValue(){
      let user = await UserManager.getUserInfo()

      this.setState({userInfo: user})
      console.log("user is", this.state.userInfo.UserName)

      let ticket = await  UserManager.getTicket()
      this.setState({ticket: ticket})

      let installedList = queryAppList()
      this.setState({installedList: installedList})

      //console.log("installedList:", installedList)
    }

      


    componentDidMount(){
      this.getAppCategory()
      const that = this
      // that.setState({isShowProgress: true})

     

      // setInterval(()=>{
      //   var pro =  this.state.progress
      //   this.updateProgressFun((pro + 1) % 100)
      //   if(pro === 99){
      //     this.setState({isShowProgress: false})
      //   }
        
      //   console.log("progress is: ", this.state.progress)
      // }, 1)

    }

    componentDidUpdate(){


     
    }

    getAppCategory(){

      //[{"Id": 3, "Name": "移动端", "Sort": 1}]
      const that = this

      getAppCategorysApi().then(async (resp) =>{

        // console.log("getAppCategorysApi resp:", resp)
        await UserManager.setCategory(resp.Result)
        that.getAppList();

      }).catch((error)=>{
        ToastUtils.showToast( error);
      });

    }

    async getAppList(){
      
     let categoryList = await  UserManager.getCategory()

     const that = this

     if(categoryList.length > 0){
       let category = categoryList[0]

       getAppsByCategorysIdApi(category.Id).then(resp=>{

        //遍历判断是否已经下載過
        resp.Result.forEach((item, index, self) => {
          
          resp.Result[index].appStatus = 0; //下载
          if(that.state.installedList.length > 0){
            that.state.installedList.forEach((didInstallItem, retindex, retself) => {
              console.log("======item.appId:", "" + item.appId)
              console.log("======didInstallItem.appId:", "" + didInstallItem.appId)
              if(didInstallItem.appId === item.appId){

                if(didInstallItem.appHisId === item.appHisId){
                  resp.Result[index].appStatus = 1; //启动
                }else{
                  resp.Result[index].appStatus = 2;  //更新
                }
               
               
              }
            });
          }
          
        });


        this.setState({appList: resp.Result})

      }).catch((error)=>{
        console.log("getAppsByCategorysIdApi error:", error)
      });

     }
      

    }

    onStartRefresh() {

      this.getDefaultValue()

      this.setState({refreshing: true})

      this.getAppList()
       
      this.setState({refreshing: false})

      
      
    }

    renderItem = ({ item }) => (
        <AppListItem item={item} itemClick={() => { 
           this.onItemClick(item)
         }} />
    );

    onItemClick(item){

      console.log("item:", item)

      if(item.appStatus === 0){
        this.installItem(item)
      }else if(item.appStatus === 1){
        // this.props.navigation.navigate('WebviewPage',{item: item});
        this.installItem(item)
      }else if(item.appStatus === 2){
        this.installItem(item)
      }
     


      
    }

    // 下载应用
   installItem(item){

      //点击安装，先判断是否存在，存在就打开，不存在就下载
      let pathName = Constants.documentPath + '/' + item.appId + '/' + item.appHisId;
      let dirPathName =  Constants.documentPath + '/' + item.appId;
      let fileName = item.appHisId + '.zip'

      //console.log("call install:", item.appName)
      let srcPath = Constants.downUrl + "/RF_Attachment/" + item.appFilePath.replace('\\', '/')
      // let srcPath = "http://192.168.34.58:8081/projects/check_code/dist/dist.zip"
      const that = this;

      //console.log("installItem call====", item)

      RNFS.exists(pathName).then(exists => {
        if (exists) {
          //forTest
          RNFS.unlink(pathName);
          //直接打开
        }
        //  else {

          const options = {
            NSURLIsExcludedFromBackupKey: true, // iOS only
          };
         
          RNFS.exists(dirPathName).then(exists => {
            if (exists) {
              // //删除文件
              RNFS.unlink(dirPathName);
            }
      

            console.log('mkdir:' + pathName);
           RNFS.mkdir(pathName, options);
           that.downLoadFile(srcPath, pathName, fileName, item)
           
          });

      
         
      
        // }
      });


     

    }

    updateProgressFun(pro){
      this.setState({progress:pro})
    }

   

   downLoadFile(srcPath, pathName, fileName, item){
    this.setState({isShowProgress: true})
      const that = this
      var currentProgress = -1
        //下载文件http://192.168.34.58:8081/proj/1.zip
        FileUtil.downloadH5File(srcPath, pathName, fileName,(res)=>{

          
            var pro = parseInt((res.bytesWritten / res.contentLength * 100) % 100) ;
           

            that.updateProgressFun(pro)
            currentProgress = pro
    
  

        } ).then((res)=>{
          console.log('success download====');

          that.setState({isShowProgress: false})

          FileUtil.unzipFile(pathName, fileName).then((path) => {
            const sourcePath = pathName + "/" + fileName;
            console.log(`unzip completed at ${path}`);
            //解压完成，删掉压缩包
            RNFS.unlink(sourcePath);

            item.localPath = path
            if(item.appType == null){
              item.appType = ''
            }
            if(item.target == null){
              item.target = ''
            }
            insertAppInfos([item]);

          })
          .catch((error) => {
            //解压失败
            console.error("解压失败", error);
          });
        }).catch((err)=>{
          console.log('downloadH5File err:', err);
        })
    }
    


    render(){
     
        return (
          <SafeAreaView>
           
           <FlatList
          data={this.state.appList}
          renderItem={this.renderItem}
          keyExtractor={item => item.appId}
          //下拉刷新
          refreshing={this.state.refreshing}
          onRefresh={() => {
            this.onStartRefresh();
          }}
          />

          {
              this.state.isShowProgress ? <ProgressHub  progress={this.state.progress}/> : null
            }
          </SafeAreaView>

    

        );
    }
}